package com.zm.zyz.servlet;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.gson.Gson;
import com.zm.zyz.util.MyBatisHelper;
import com.zm.zyz.entity.ZyzUser;
import com.zm.zyz.mapper.ZyzUserMapper;
import com.zm.zyz.vo.Result;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static com.zm.zyz.util.Utils.print;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name");
        String pwd = req.getParameter("pwd");
        if(name == null || name.isBlank()){
            print(resp,new Result(0,"请输入账号！",null));
            return;
        }

        if(pwd == null || pwd.isBlank()){
            print(resp,new Result(0,"请输入密码！",null));
            return;
        }

        SqlSession session = MyBatisHelper.getSession();
        ZyzUserMapper userMapper = session.getMapper(ZyzUserMapper.class);
        LambdaQueryWrapper<ZyzUser> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ZyzUser::getName,name);
        lqw.eq(ZyzUser::getPwd,pwd);
        ZyzUser user = userMapper.selectOne(lqw);
        if (user==null){
            print(resp,new Result(0,"用户名或密码错误",null));
            return;
        }
        req.getSession().setAttribute("loginedUser",user);
        print(resp,new Result(1,"登陆成功！",user));
    }


}
